const express = require("express");
const Store = require("../models/storeModel");
const storeSystem = require("../models/storeSystemModel");
const { authMiddleware, hasPermission } = require("../middleware/authMiddleware");

const router = express.Router();

/* ==================== STORE ROUTES ==================== */

// CREATE a new Store
router.post("/add/Store", authMiddleware, hasPermission("Stores", "Add"), async (req, res) => {
  try {
    const {
      StoreCode,
      StoreName,
      Mobile,
      Email,
      Phone,
      Gst_Number,
      Tax_Number,
      Pan_Number,
      Store_website,
      Bank_details,
      Country,
      State,
      City,
      PostCode,
      Address,
      Latitude,
      Longitude,
    } = req.body;
    
    // Construct the GeoJSON location field if latitude and longitude are provided
    let location;
    if (Latitude != null && Longitude != null) {
      location = {
        type: "Point",
        coordinates: [Number(Longitude), Number(Latitude)]
      };
    }
    
    const newStore = new Store({
      StoreCode,
      StoreName,
      Mobile,
      Email,
      Phone,
      Gst_Number,
      Tax_Number,
      Pan_Number,
      Store_website,
      Bank_details,
      Country,
      State,
      City,
      PostCode,
      Address,
      Latitude,
      Longitude,
      location  // include location explicitly
    });
    
    const result = await newStore.save();
    res.status(200).json({ message: "Data Saved Successfully", result });
  } catch (error) {
    res.status(500).json({ message: "Internal Server Error", error: error.message });
  }
});

// GET all Stores (or filter by proximity if latitude & longitude are provided)
router.get("/add/store", authMiddleware, hasPermission("Stores", "View"), async (req, res) => {
  try {
    let query = Store.find({});
    if (req.query.latitude && req.query.longitude) {
      const lat = parseFloat(req.query.latitude);
      const lng = parseFloat(req.query.longitude);
      const maxDistance = parseInt(req.query.maxDistance) || 5000; // default 5000 meters
      
      query = Store.find({
        location: {
          $near: {
            $geometry: { type: "Point", coordinates: [lng, lat] },
            $maxDistance: maxDistance
          }
        }
      });
    }
    
    const result = await query.exec();
    res.status(200).json({ message: "Data Fetched Successfully", result });
  } catch (err) {
    res.status(500).json({ message: "Internal Server Error", err });
  }
});

// UPDATE a Store by ID
router.put("/store/:id", authMiddleware, hasPermission("Stores", "Edit"), async (req, res) => {
  try {
    const { id } = req.params;
    const {
      StoreCode,
      StoreName,
      Mobile,
      Email,
      Phone,
      Gst_Number,
      Tax_Number,
      Pan_Number,
      Store_website,
      Bank_details,
      Country,
      State,
      City,
      PostCode,
      Address,
      Latitude,
      Longitude,
    } = req.body;
    
    let location;
    if (Latitude != null && Longitude != null) {
      location = {
        type: "Point",
        coordinates: [Number(Longitude), Number(Latitude)]
      };
    }
    
    const updatedStore = await Store.findByIdAndUpdate(
      id,
      {
        StoreCode,
        StoreName,
        Mobile,
        Email,
        Phone,
        Gst_Number,
        Tax_Number,
        Pan_Number,
        Store_website,
        Bank_details,
        Country,
        State,
        City,
        PostCode,
        Address,
        Latitude,
        Longitude,
        location,
      },
      { new: true }
    );
    
    if (!updatedStore) {
      return res.status(404).json({ message: "Store not found" });
    }
    res.status(200).json({ message: "Store updated successfully", updatedStore });
  } catch (error) {
    res.status(500).json({ message: "Internal Server Error", error: error.message });
  }
});

// DELETE a Store by ID
router.delete("/store/:id", authMiddleware, hasPermission("Stores", "Delete"), async (req, res) => {
  try {
    const { id } = req.params;
    const deletedStore = await Store.findByIdAndDelete(id);
    if (!deletedStore) {
      return res.status(404).json({ message: "Store not found" });
    }
    res.status(200).json({ message: "Store deleted successfully", deletedStore });
  } catch (error) {
    res.status(500).json({ message: "Internal Server Error", error: error.message });
  }
});

/* ==================== SYSTEM ZONE ROUTES ==================== */

// CREATE a new System Zone
router.post("/add/systemzone", authMiddleware, hasPermission("systemzone", "Add"), async (req, res) => {
  try {
    const {
      Timezone,
      Dateformat,
      TimeFormat,
      Currency,
      CurrencySymbolPlacement,
      Decimals,
      DecimalforQuantity,
      Language,
    } = req.body;
    
    const newSystemZone = new storeSystem({
      Timezone,
      Dateformat,
      TimeFormat,
      Currency,
      CurrencySymbolPlacement,
      Decimals,
      DecimalforQuantity,
      Language,
    });
    
    const data = await newSystemZone.save();
    res.status(200).json({ message: "Data saved successfully", data });
  } catch (error) {
    res.status(500).json({ message: "Internal Server Error", error: error.message });
  }
});

// UPDATE a System Zone by ID
router.put("/systemzone/:id", authMiddleware, hasPermission("systemzone", "Edit"), async (req, res) => {
  try {
    const { id } = req.params;
    const {
      Timezone,
      Dateformat,
      TimeFormat,
      Currency,
      CurrencySymbolPlacement,
      Decimals,
      DecimalforQuantity,
      Language,
    } = req.body;
    
    const updatedSystemZone = await storeSystem.findByIdAndUpdate(
      id,
      {
        Timezone,
        Dateformat,
        TimeFormat,
        Currency,
        CurrencySymbolPlacement,
        Decimals,
        DecimalforQuantity,
        Language,
      },
      { new: true }
    );
    
    if (!updatedSystemZone) {
      return res.status(404).json({ message: "System Zone not found" });
    }
    
    res.status(200).json({ message: "System Zone updated successfully", data: updatedSystemZone });
  } catch (error) {
    res.status(500).json({ message: "Internal Server Error", error: error.message });
  }
});

// DELETE a System Zone by ID
router.delete("/systemzone/:id", authMiddleware, hasPermission("systemzone", "Delete"), async (req, res) => {
  try {
    const { id } = req.params;
    const deletedSystemZone = await storeSystem.findByIdAndDelete(id);
    if (!deletedSystemZone) {
      return res.status(404).json({ message: "System Zone not found" });
    }
    res.status(200).json({ message: "System Zone deleted successfully", data: deletedSystemZone });
  } catch (error) {
    res.status(500).json({ message: "Internal Server Error", error: error.message });
  }
});

module.exports = router;
